/**
 * There are <a href="https://github.com/thinkgem/jeesite">JeeSite</a> code generation
 */
package com.boxin.ims.modules.wechat.web;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;
import com.boxin.ims.modules.wechat.entity.Option;
import com.boxin.ims.modules.wechat.entity.Question;
import com.boxin.ims.modules.wechat.entity.Questionnaire;
import com.boxin.ims.modules.wechat.entity.activity.ActivityConfig;
import com.boxin.ims.modules.wechat.service.OptionService;
import com.boxin.ims.modules.wechat.service.QuestionService;
import com.boxin.ims.modules.wechat.service.QuestionnaireReplyService;
import com.boxin.ims.modules.wechat.service.QuestionnaireService;
import com.boxin.ims.modules.wechat.service.WechatDaoHelper;
import com.boxin.ims.modules.wechat.service.activity.ActivityConfigService;

/**
 * 调查问卷Controller
 * @author XiaoQian
 * @version 2014-05-09
 */
@Controller
@RequestMapping(value = Global.ADMIN_PATH+"/wechat/questionnaire")
public class QuestionnaireController extends BaseController {

	@Autowired
	private QuestionnaireService questionnaireService;
	
	@Autowired
	private QuestionService questionService;
	
	@Autowired
	private OptionService optionService;
	
	@Autowired
	private QuestionnaireReplyService questionnaireReplyService;
	
	@Autowired
	private ActivityConfigService activityConfigService;
	
	@Autowired
	private WechatDaoHelper wechatDaoHelper;
	
	
	@ModelAttribute
	public Questionnaire get(@RequestParam(required=false) Long id) {
		if (id != null){
			return questionnaireService.get(id);
		}else{
			return new Questionnaire();
		}
	}
	
	@RequiresPermissions("wechat:questionnaire:view")
	@RequestMapping(value = {"list", ""})
	public String list(Questionnaire questionnaire, HttpServletRequest request, HttpServletResponse response, Model model) {
		User user = UserUtils.getUser();
		if (!user.isAdmin()){
			questionnaire.setUser(user);
		}
        Page<Questionnaire> page = questionnaireService.find(new Page<Questionnaire>(request, response), questionnaire); 
        model.addAttribute("page", page);
		return "modules/wechat/questionnaireList";
	}

	@RequiresPermissions("wechat:questionnaire:view")
	@RequestMapping(value = "form")
	public String form(Questionnaire questionnaire, Model model) {
		
		
		User user = UserUtils.getUser();
		if (questionnaire.getUser() == null || questionnaire.getUser().getId() <1){
			questionnaire.setUser(user);
		}
		ActivityConfig activityConfig=new ActivityConfig();
		activityConfig.setUser(user);
		List<ActivityConfig> activityConfigList= activityConfigService.find(activityConfig);
		
		
		model.addAttribute("questionnaire", questionnaire);
		model.addAttribute("activityConfigList", activityConfigList);
		if(questionnaire!=null&&questionnaire.getType()!=null&&questionnaire.getType().equals("0")){
			return "modules/wechat/questionnaireForm";
		}else if(questionnaire!=null&&questionnaire.getType()!=null&&questionnaire.getType().equals("1")){
			return "modules/wechat/fightingForm";
		}else{
			return "modules/wechat/voteForm";
		}
	}

	@RequiresPermissions("wechat:questionnaire:edit")
	@RequestMapping(value = "save")
	public String save(Questionnaire questionnaire, Model model, RedirectAttributes redirectAttributes, HttpServletRequest request) {
		EntityManager entityManager =questionnaireService.getEntityManager();
		EntityManagerFactory entityManagerFactory = entityManager.getEntityManagerFactory();
		/* 清除实体缓存 */
		entityManager.clear();
		entityManagerFactory.getCache().evict(ActivityConfig.class);
		entityManagerFactory.getCache().evict(Questionnaire.class);
		if (!beanValidator(model, questionnaire)){
			return form(questionnaire, model);
		}
		questionnaireService.save(questionnaire);
		addMessage(redirectAttributes, "保存调查问卷'" + questionnaire.getName() + "'成功");
		return "redirect:"+Global.ADMIN_PATH+"/wechat/questionnaire/?repage";
	}
	
	@RequiresPermissions("wechat:questionnaire:edit")
	@RequestMapping(value = "delete")
	public String delete(Long id, RedirectAttributes redirectAttributes) {
		
		List<Question> questionList=questionService.findByQuestionnaireId(id);
		
		for (int i = 0; i < questionList.size(); i++) {
			
			Iterator<Option> it=questionList.get(i).getOption().iterator();
			
			while (it.hasNext()) {
				Option option = it.next();
				optionService.delete(option.getId());
			}
			questionService.delete(questionList.get(i).getId());
		}
		
		questionnaireService.delete(id);
		addMessage(redirectAttributes, "删除调查问卷成功");
		return "redirect:"+Global.ADMIN_PATH+"/wechat/questionnaire/?repage";
	}
	
	
	@RequestMapping(value = "questionnaireResult")
	public String  questionnaireResult(Long id, Model model, RedirectAttributes redirectAttributes) {
		
		List<Question> questionList= questionService.findByQuestionnaireId(id);
		
		
		
		Map<String, Integer> map=new HashMap<String, Integer>();
		Map<String, Integer> questionConutMap=new HashMap<String, Integer>();
		
		for (int i = 0; i < questionList.size(); i++) {
			 Iterator<Option> iterator= questionList.get(i).getOption().iterator();
			 List<Map<String, Object>>  list= new ArrayList<Map<String, Object>>();
			 if(!questionList.get(i).getType().equals("2")){
				 	Map<String, Object> params=new HashMap<String, Object>();
					params.put("question_id",questionList.get(i).getId());
					
					list= wechatDaoHelper.selectquestionnaireReplyByQuestionId(params);
					
					questionConutMap.put(questionList.get(i).getId().toString(), list.size());
				 if(questionList.get(i).getType().equals("0")){
					 
					 while (iterator.hasNext()) {
						 Option option = iterator.next();
						 
						 map.put(option.getId()+"", 0);
						 for (int j = 0; j < list.size(); j++) {
							 if(option.getName().equals(String.valueOf(list.get(j).get("answer")))){
								 map.put(option.getId()+"", map.get(option.getId()+"")+1);
							 }
						 }
					 }
				 }
				 if(questionList.get(i).getType().equals("1")){
					 while (iterator.hasNext()) {
						 Option option = iterator.next();
						 
						 map.put(option.getId()+"", 0);
						 for (int j = 0; j < list.size(); j++) {
							 String answer= list.get(j).get("answer").toString();
							 String[] str= answer.split(",");
							 for (int k = 0; k < str.length; k++) {
								 if(option.getName().equals(str[k] )){
									 map.put(option.getId()+"", map.get(option.getId()+"")+1);
								 }
							}
						 }
					 }
				 }
			 }
		}
		
		model.addAttribute("questionList", questionList);
		model.addAttribute("map", map);
		model.addAttribute("questionConutMap", questionConutMap);
		
		return "modules/wechat/questionnaireResultList";
	}
	
	
	@RequestMapping(value = "getQuestionById")
	public String getQuestionById(Long id, RedirectAttributes redirectAttributes,Model model) {
		
		Map<String, Object> map =new HashMap<String,Object>();
		
		map.put("question_id", id);
		
		List<Map<String, Object>> list= wechatDaoHelper.getQuestionType3ById(map);
		
		
		model.addAttribute("list", list);
		return "modules/wechat/questionType3List";
	}
	
	
	
	@RequestMapping(value = "startupQuestionnaire")
	public String startupQuestionnaire(Long id, RedirectAttributes redirectAttributes,Model model) {
		Questionnaire questionnaire=   questionnaireService.get(id);
		
		
		questionnaireService.updateByUserId(questionnaire.getUser().getId());
		
		
		questionnaire.setStartup("0");
		questionnaireService.save(questionnaire);
		
		addMessage(redirectAttributes, "该问题开启");
		return "redirect:"+Global.ADMIN_PATH+"/wechat/questionnaire/?repage";
	}
	
	
	@RequestMapping(value = "closedownQuestionnaire")
	public String closedownQuestionnaire(Long id, RedirectAttributes redirectAttributes,Model model) {
		Questionnaire questionnaire=   questionnaireService.get(id);
		questionnaire.setStartup("1");
		questionnaireService.save(questionnaire);
		
		addMessage(redirectAttributes, "该问题关闭");
		return "redirect:"+Global.ADMIN_PATH+"/wechat/questionnaire/?repage";
	}
	
	
	@RequestMapping(value = "getWechatMessage")
	public String getWechatMessage( RedirectAttributes redirectAttributes,Model model,HttpServletRequest request) {
		
		String pageNo=request.getParameter("pageNo");
		String pageSize=request.getParameter("pageSize");
		
		Integer no =1;
		Integer size =20;
		
		if (StringUtils.isNumeric(pageNo)){
			no=Integer.parseInt(pageNo);
		}
		if(StringUtils.isNumeric(pageSize)){
			size=Integer.parseInt(pageSize);
		}
		
		
		Map<String, Object> params =new HashMap<String ,Object>();
		
		params.put("user_id", "430000012");
		params.put("message", "靳府酒+%");
		List<Map<String, Object>>  count=  wechatDaoHelper.getWechatMessageSourceCount(params);
		params.put("pagesize", 20);
		params.put("pageindex",(no-1)*20 );
		
		List<Map<String, Object>>  list=  wechatDaoHelper.getWechatMessageSource(params);
		
		
		Page page =new Page(no, size,Integer.parseInt(count.get(0).get("count").toString()), list);
		
		model.addAttribute("page", page);
		return "modules/wechat/getWechatMessageList";
	}

}
